import '../models/period_model.dart';
import '../services/database_helper.dart';
import 'base_repository.dart';
import '../utils/date_utils.dart' as custom_date_utils;


class UserProfileRepositoryImpl implements UserProfileRepository {
  final DatabaseHelper _databaseHelper;

  UserProfileRepositoryImpl(this._databaseHelper);

  @override
  Future<UserProfile?> getById(int id) async {
    final db = await _databaseHelper.database;
    final maps = await db.query(
      DatabaseHelper.tableUser,
      where: '${DatabaseHelper.columnUserId} = ?',
      whereArgs: [id],
      limit: 1,
    );

    if (maps.isNotEmpty) {
      return UserProfile.fromMap(maps.first);
    }
    return null;
  }

  @override
  Future<List<UserProfile>> getAll() async {
    final db = await _databaseHelper.database;
    final maps = await db.query(DatabaseHelper.tableUser);
    return maps.map((map) => UserProfile.fromMap(map)).toList();
  }

  @override
  Future<int> save(UserProfile entity) async {
    final db = await _databaseHelper.database;
    return await db.insert(DatabaseHelper.tableUser, _toMap(entity));
  }

  @override
  Future<bool> update(UserProfile entity) async {
    final db = await _databaseHelper.database;
    final rowsAffected = await db.update(
      DatabaseHelper.tableUser,
      _toMap(entity),
      where: '${DatabaseHelper.columnUserId} = ?',
      whereArgs: [entity.id],
    );
    return rowsAffected > 0;
  }

  @override
  Future<bool> delete(int id) async {
    final db = await _databaseHelper.database;
    final rowsAffected = await db.delete(
      DatabaseHelper.tableUser,
      where: '${DatabaseHelper.columnUserId} = ?',
      whereArgs: [id],
    );
    return rowsAffected > 0;
  }

  @override
  Future<UserProfile?> getFirstProfile() async {
    final db = await _databaseHelper.database;
    final maps = await db.query(
      DatabaseHelper.tableUser,
      limit: 1,
    );

    if (maps.isNotEmpty) {
      return UserProfile.fromMap(maps.first);
    }
    return null;
  }

  
  Map<String, dynamic> _toMap(UserProfile profile) {
    return {
      DatabaseHelper.columnUserName: profile.name,
      DatabaseHelper.columnUserDOB: custom_date_utils.DateUtils.formatDate(profile.birthDate),
      DatabaseHelper.columnUserHeight: profile.height,
      DatabaseHelper.columnUserWeight: profile.weight,
      DatabaseHelper.columnUserBloodType: profile.bloodType,
      DatabaseHelper.columnUserCycle: profile.cycleLength,
      DatabaseHelper.columnUserPeriod: profile.periodLength,
      DatabaseHelper.columnUserMode: profile.currentMode,
      'healthConditions': profile.healthConditions.join(','),
      'isUsingBirthControl': profile.isUsingBirthControl ? 1 : 0,
      // 将不存在的列移至用户设置表中管理
      // 对于 lastPeriodDate, notificationsEnabled, darkMode, reminderDays 等字段，
      // 应该在用户设置表中存储
      DatabaseHelper.columnUserLastLogin: DateTime.now().toIso8601String(),
    };
  }
}